package com.hrbxlh.action;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.hrbxlh.actionImpl.*;
import com.hrbxlh.dao.MyCourseDao;
import com.hrbxlh.dao.RelationDao;
import com.hrbxlh.util.ConfigFileUtil;
import com.hrbxlh.util.SessionValues;
import com.hrbxlh.virtualization.service.ImageAllocationService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/FishboneDiagramAction")
public class FishboneDiagramAction {

	@Autowired
	@Qualifier("courseActionImpl")
	private CourseActionImpl courseActionImpl;

	@Autowired
	@Qualifier("chapterActionImpl")
	private ChapterActionImpl chapterActionImpl;

	@Autowired
	@Qualifier("myCourseActionImpl")
	private MyCourseActionImpl myCourseActionImpl;

	@Autowired
	@Qualifier("homeworkTestActionImpl")
	private HomeworkTestActionImpl homeworkTestActionImpl;

	@Autowired
	@Qualifier("departMentActionImpl")
	private DepartMentActionImpl departMentActionImpl;

	@Autowired
	@Qualifier("relationActionImpl")
	private RelationActionImpl relationActionImpl;

	@Autowired
	private ImageAllocationService imageAllocationService;

	@Resource(name="myCourseDao")
	private MyCourseDao myCourseDao;

	@Resource(name = "relationDao")
	private RelationDao relationDao;

	Logger logger = Logger.getLogger(CourseAction.class.getName());

	private HashMap<String, String> BooleanMap = new HashMap();
	private HashMap<String, String> BooleanMap2 = new HashMap();
	private HashMap<String, String> BooleanMap3 = new HashMap();
	private HashMap<String, String> BooleanMap4 = new HashMap();

	@RequestMapping(value = "/FishboneDiagramActionInfo", method = RequestMethod.GET)
	public void FishboneDiagramActionInfo(HttpServletRequest request, HttpServletResponse response,@RequestParam String xqcount)  {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> coursermap = new HashMap<String, Object>();
		try {
			List<Map<String, Object>> courseList;
			SessionValues session = new SessionValues();
			Map<String, Object> sessionValues = session.getSessionValues(new String[]{"roleId", "stuorteaId"}, request, "userMsg");
//			resultMap.put("roleId", sessionValues.get("roleId"));
//			resultMap.put("stuorteaId", sessionValues.get("stuorteaId"));
			String[] keysArray = {"server_address", "project_name"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			String url = (String)urlmap.get("server_address")+(String)urlmap.get("project_name")+"upload/course/";
			resultMap.put("url", url);
			List<Map<String, Object>> courseListinfo= Lists.newArrayList();
			String testDocName="";
			String coursewareName="";
			String resources="";
//			if (Integer.valueOf(sessionValues.get("roleId").toString())==1){
//				courseList=myCourseDao.getStuCourse(resultMap);
//			}else {
//				courseList= myCourseDao.getTeacherCourse(resultMap);
//			}
			resultMap.put("releaseMark", 1);
			resultMap.put("saveMark", null);
			courseList = relationDao.courseListOther(resultMap);
			//courseList = myCourseActionImpl.getMyCourse(resultMap);
			resultMap.put("inMark", 1);
			resultMap.put("saveMark", 1);
			if (courseList != null) {
				for (int i = 0; i < courseList.size(); i++) {
					Map<String, Object> mapcourse=new HashMap<>();

					String courseId= courseList.get(i).get("courseId") == null ? "" : courseList.get(i).get("courseId").toString();
					String courseName= courseList.get(i).get("courseName") == null ? "" : courseList.get(i).get("courseName").toString();
					sessionValues.put("courseId",courseId);
					List<Map<String, Object>> chapterList = chapterActionImpl.getCourseChapterNotFileInfo(sessionValues);
					List<Map<String, Object>> chapterListinfo= Lists.newArrayList();
					for (int j = 0; j < chapterList.size(); j++) {
						Map<String, Object> mapchapter=new HashMap<>();
						String chapterId = chapterList.get(j).get("chapterId").toString();
						String chapterName = chapterList.get(j).get("chapterName").toString();
						String addTestMark = chapterList.get(j).get("addTestMark").toString();
						if (Integer.valueOf(chapterList.get(j).get("addTestMark").toString())!=2){
							testDocName= chapterList.get(j).get("testDocName")==null?"":chapterList.get(j).get("testDocName").toString();
							mapchapter.put("resourcesName",testDocName);
						}else {
							coursewareName= chapterList.get(j).get("coursewareNameHtml")==null?"":chapterList.get(j).get("coursewareNameHtml").toString();
							mapchapter.put("resourcesName",coursewareName);
						}
						mapchapter.put("addTestMark",addTestMark);
						mapchapter.put("chapterId",chapterId);
						mapchapter.put("chapterName",chapterName);
						chapterListinfo.add(mapchapter);
					}
					mapcourse.put("chapterList",chapterListinfo);
					mapcourse.put("courseId",courseId);
					mapcourse.put("courseName",courseName);
					if (xqcount.equals("1")){
						if (!BooleanMap.containsKey(courseId)){
							courseListinfo.add(mapcourse);
						}
					}
					if (xqcount.equals("2")){
						if (!BooleanMap2.containsKey(courseId)){
							courseListinfo.add(mapcourse);
						}
					}
					if (xqcount.equals("3")){
						if (!BooleanMap3.containsKey(courseId)){
							courseListinfo.add(mapcourse);
						}
					}
					if (xqcount.equals("4")){
						if (!BooleanMap4.containsKey(courseId)){
							courseListinfo.add(mapcourse);
						}
					}
				}
				resultMap.put("courseList", courseListinfo);
			}
			resultMap.put("result", "success");
			courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("result", "fail");
			logger.error("查询课程出现异常", e);
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
	}
	@RequestMapping(value = "/UpdateFishboneDiagramActionInfo", method = RequestMethod.POST)
	public void SaveFishboneDiagramActionInfo(HttpServletRequest request, HttpServletResponse response, String jsonStr,@RequestParam String xqcount)  {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		ObjectMapper mapper = new ObjectMapper();
		Map<String, Object> returnMap = new HashMap<String, Object>();
		try {
			Map<String, Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			String updateInfo = paramMap.get("updateInfo").toString();
			String courseIds = paramMap.get("courseId").toString();
			String courseNames = paramMap.get("courseName").toString();
			if ("save".equals(updateInfo)) {
				String[] courseId = courseIds.split(",");
				String[] courseName = courseNames.split(",");
				for (int i = 0; i < courseId.length; i++) {
					if (xqcount.equals("1")){
						if (!BooleanMap.containsKey(courseId)){
							BooleanMap.remove(courseId[i]);
						}
					}
					if (xqcount.equals("2")){
						if (!BooleanMap2.containsKey(courseId)){
							BooleanMap2.remove(courseId[i]);
						}
					}
					if (xqcount.equals("3")){
						if (!BooleanMap3.containsKey(courseId)){
							BooleanMap3.remove(courseId[i]);
						}
					}
					if (xqcount.equals("4")){
						if (!BooleanMap4.containsKey(courseId)){
							BooleanMap4.remove(courseId[i]);
						}
					}


				}
			} else {
				if (xqcount.equals("1")){

					BooleanMap.put(courseIds,courseNames);

				}
				if (xqcount.equals("2")){

					BooleanMap2.put(courseIds,courseNames);

				}
				if (xqcount.equals("3")){

					BooleanMap3.put(courseIds,courseNames);

				}
				if (xqcount.equals("4")){

					BooleanMap4.put(courseIds,courseNames);

				}

			}
			resultMap.put("result", "success");
			courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
		} catch (IOException e) {
			e.printStackTrace();
			resultMap.put("result", "fail");
			logger.error("添加课程信息出现异常", e);
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
	}
	@RequestMapping(value = "/query", method = RequestMethod.POST)
	public void query(HttpServletRequest request, HttpServletResponse response, @RequestParam String xqcount) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> list= Lists.newArrayList();
		ObjectMapper mapper = new ObjectMapper();
		resultMap.put("result", "success");
		try {
			if (BooleanMap.size()==0){
//				resultMap.put("releaseMark", 1);
//				resultMap.put("saveMark", 0);
//				List<Map<String, Object>> allReList = relationDao.courseList(resultMap);
//				if (allReList != null) {
//					for (int i = 0; i < allReList.size(); i++) {
//						Map<String, Object> mapcourse=new HashMap<>();
//						String courseId= allReList.get(i).get("courseId") == null ? "" : allReList.get(i).get("courseId").toString();
//						String courseName= allReList.get(i).get("courseName") == null ? "" : allReList.get(i).get("courseName").toString();
//						if (xqcount.equals("1")){
//							BooleanMap.put(courseId,courseName);
//						}
//						if (xqcount.equals("2")){
//							BooleanMap2.put(courseId,courseName);
//						}
//						if (xqcount.equals("3")){
//							BooleanMap3.put(courseId,courseName);
//						}
//						if (xqcount.equals("4")){
//							BooleanMap4.put(courseId,courseName);
//						}
//					}
//				}
//				BooleanMap.put("begin","begin");
//				BooleanMap2.put("begin","begin");
//				BooleanMap3.put("begin","begin");
//				BooleanMap4.put("begin","begin");
				install(resultMap,xqcount,BooleanMap);
			}
			if (BooleanMap2.size()==0){
				install(resultMap,xqcount,BooleanMap2);
			}
			if (BooleanMap3.size()==0){
				install(resultMap,xqcount,BooleanMap3);
			}
			if (BooleanMap4.size()==0){
				install(resultMap,xqcount,BooleanMap4);
			}
//			resultMap.put("listinfo", BooleanMap);
//			Iterator iter = BooleanMap.keySet().iterator();
//			while (iter.hasNext()){
//				String key = iter.next().toString();
//				if (!"begin".equals(key)){
//				String value = BooleanMap.get(key);
//				Map<String, Object> resultMapnew  = new HashMap<String, Object>();
//				resultMapnew.put("label",value);
//				resultMapnew.put("value",key);
//				list.add(resultMapnew);
//				}
//			}
			List list1 = queryOther(BooleanMap);
			List list2 = queryOther(BooleanMap2);
			List list3 = queryOther(BooleanMap3);
			List list4 = queryOther(BooleanMap4);
			if (xqcount.equals("1")){
				resultMap.put("listinfo",list1);
			}
			if (xqcount.equals("2")){
				resultMap.put("listinfo",list2);
			}
			if (xqcount.equals("3")){
				resultMap.put("listinfo",list3);
			}
			if (xqcount.equals("4")){
				resultMap.put("listinfo",list4);
			}
			courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("result", "fail");
			logger.error("查询课程出现异常", e);
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}
	private  List  queryOther(Map map){
		List list=Lists.newArrayList();
		Iterator iter = map.keySet().iterator();
		while (iter.hasNext()){
			String key = iter.next().toString();
			if (!"begin".equals(key)){
				String value = map.get(key).toString();
				Map<String, Object> resultMapnew  = new HashMap<String, Object>();
				resultMapnew.put("label",value);
				resultMapnew.put("value",key);
				list.add(resultMapnew);
			}
		}
		return  list;
	}
	private  void  install(Map<String, Object> resultMap,String xqcount,Map map) throws Exception {

		resultMap.put("releaseMark", 1);
		resultMap.put("saveMark", 0);
		List<Map<String, Object>> allReList = relationDao.courseList(resultMap);
		if (allReList != null) {
			for (int i = 0; i < allReList.size(); i++) {
				Map<String, Object> mapcourse=new HashMap<>();
				String courseId= allReList.get(i).get("courseId") == null ? "" : allReList.get(i).get("courseId").toString();
				String courseName= allReList.get(i).get("courseName") == null ? "" : allReList.get(i).get("courseName").toString();
				if (xqcount.equals("1")){
					BooleanMap.put(courseId,courseName);
					BooleanMap.put("begin","begin");
				}
				if (xqcount.equals("2")){
					BooleanMap2.put(courseId,courseName);
					BooleanMap2.put("begin","begin");
				}
				if (xqcount.equals("3")){
					BooleanMap3.put(courseId,courseName);
					BooleanMap3.put("begin","begin");
				}
				if (xqcount.equals("4")){
					BooleanMap4.put(courseId,courseName);
					BooleanMap4.put("begin","begin");
				}
			}
		}


	}
}

